package com.manong.bookstore.user.controller;

import com.manong.common.utils.R;
import com.manong.bookstore.user.entity.AddressEntity;
import com.manong.bookstore.user.entity.UserEntity;
import com.manong.bookstore.user.feign.*;
import com.manong.bookstore.user.util.CookieFinder;
import com.manong.bookstore.user.util.UserSessionTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("user/page")
public class PageController {
	@Autowired
	private UserFeignService userFeignService;
	@Autowired
	private SearchFeignService searchFeignService;
	@Autowired
	private StoreFeignService storeFeignService;
	@Autowired
	private ShoppingcartFeignService shoppingcartFeignService;
	@Autowired
	private MessageFeignService messageFeignService;

	@Value("${iconSavePath}")
	private String iconSavePath;
	@Value("${iconBasePath}")
	private String iconBasePath;

	@RequestMapping("/index")
	public String index(Model model, HttpSession session){
		session.setAttribute("userId", 123);
		return "redirect:http://localhost:88/to_user/index.html";
	}

	@RequestMapping("/test")
	@ResponseBody
	public String test(@RequestBody UserEntity user, HttpServletRequest request){
		Integer userId = UserSessionTool.getUserId(userFeignService, request);

		userFeignService.save(user);

		return userId != null ? userId.toString() : "null";
	}

	/**(2020-09-08)
	 * 检查登录
	 */
	@RequestMapping("/check/login")
	@ResponseBody
	public R checkLogin(HttpServletRequest request) {
		Integer userId = UserSessionTool.getUserId(userFeignService, request);
		String userName = UserSessionTool.getUserName(userFeignService, request);

		if(userId == null)
			return R.ok().put("status", "error: no login");
		else
			return R.ok().put("status", "ok").put("userId", userId).put("userName", userName);
	}

	/**(2020-09-06)
	 * 退出登录
	 */
	@RequestMapping("/logout")
	@ResponseBody
	public R logout(HttpServletRequest request) {
		Cookie cookie = CookieFinder.findCookie(request, "USERSESSION");

		if(cookie != null) {
			boolean status = userFeignService.remove(cookie.getValue());

			if(status)
				return R.ok().put("status", "ok");
		}

		return R.ok().put("status", "error: no login");
	}

	/**(2020-09-06)
	 * 用户信息初始化
	 * 自动检查当前用户是否已登录
	 */
	@RequestMapping("/init/info")
	@ResponseBody
	public R initInfo(HttpServletRequest request) {
		Integer userId = UserSessionTool.getUserId(userFeignService, request);

		System.out.println("initInfo: " + userId);

		if(userId == null)
			return R.ok().put("status", "error: no login");

		HashMap<String, Object> params = new HashMap<>();
		params.put("userId", userId);
		Map<String, Object> user = (Map<String, Object>)userFeignService.info(params).get("user");

		//删除用户密码信息，防止泄露
		user.replace("password", null);
		System.out.println("initInfo: " + user);

		return R.ok().put("status", "ok").put("user", user);
	}

	/**(2020-09-06)
	 * 用户收货地址信息初始化
	 * 自动检查当前用户是否已登录
	 */
	@RequestMapping("/init/address")
	@ResponseBody
	public R initAddress(HttpServletRequest request) {
		Integer userId = UserSessionTool.getUserId(userFeignService, request);

		System.out.println("initAddress: " + userId);

		if(userId == null)
			return R.ok().put("status", "error: no login");

		Map<String, Object> params = new HashMap<>();
		params.put("userId", userId);
		List address = (List)userFeignService.findUserAddress(params).get("address");

		return R.ok().put("status", "ok").put("address", address);
	}

	/**(2020-09-06)
	 * 用户收货地址信息初始化
	 * 自动检查session判断当前用户是否已登录
	 * userId(测试阶段使用)
	 * http://localhost:88/userfront/userfront/user/init/order?userId=2
	 */
	@RequestMapping("/init/order")
	@ResponseBody
	public R initOrder(HttpServletRequest request) {
		Integer userId = UserSessionTool.getUserId(userFeignService, request);

		System.out.println("initOrder: " + userId);

		if(userId == null)
			return R.ok().put("status", "error: no login");

		R result = searchFeignService.accurateOrder("userId", userId.toString());

//		System.out.println("initOrder: " + result);
//		System.out.println("initOrder: " + ((Map) result.get("accurate")).get("list"));
		return R.ok().put("status", "ok").put("order", ((Map) result.get("accurate")).get("list"));
	}

	/**(2020-09-07)
	 * 用户收藏信息初始化
	 * 自动检查session判断当前用户是否已登录
	 */
	@RequestMapping("/init/collect")
	@ResponseBody
	public R initCollect(HttpServletRequest request) {
		Integer userId = UserSessionTool.getUserId(userFeignService, request);

		System.out.println("initCollect: " + userId);

		if(userId == null)
			return R.ok().put("status", "error: no login");

		R result = searchFeignService.accurateCollect("userId", userId.toString());
		List list = (List)((Map)result.get("accurate")).get("list");
		List tmp = new ArrayList();
//		System.out.println(list);
//		System.out.println(list.getClass());
//		System.out.println(list.get(0).getClass());
		for(Object i : list) {
			Map<String, Object> collect = (Map<String, Object>)i;
			Map<String, Object> store = (Map<String, Object>)storeFeignService.info(new Integer(collect.get("storeId").toString())).get("store");

			if(store == null)
				store = new HashMap<>();

			store.put("collectId", collect.get("collectId"));

			tmp.add(store);
		}

//		System.out.println("initCollect: " + tmp);

		return R.ok().put("status", "ok").put("store", tmp).put("userId", userId);
	}

	/**(2020-09-14)
	 * 用户留言初始化
	 * 自动检查session判断当前用户是否已登录
	 */
	@RequestMapping("/init/message")
	@ResponseBody
	public R initMessage(HttpServletRequest request) {
		Integer userId = UserSessionTool.getUserId(userFeignService, request);

		System.out.println("initMessage: " + userId);

		if(userId == null)
			return R.ok().put("status", "error: no login");

		try {
			Map<String, Object> params = new HashMap<>();
			params.put("sendIdValue", userId);
			params.put("sendTypeValue", "user");
			params.put("receiveIdValue", "");
			params.put("receiveTypeValue", "");
			params.put("messageIdValue", "");
			params.put("contentValue", "");
			R send = messageFeignService.LikeList(params);

			params.put("sendIdValue", "");
			params.put("sendTypeValue", "");
			params.put("receiveIdValue", userId);
			params.put("receiveTypeValue", "user");
			params.put("messageIdValue", "");
			params.put("contentValue", "");
			R receive = messageFeignService.LikeList(params);

			return R.ok().put("status", "ok").put("send", send.get("page")).put("receive", receive.get("page"));
		}
		catch (Exception e) {
			return R.ok().put("status", "error: server error");
		}
	}



	/**(2020-09-06)
	 * 修改用户信息（邮箱、密码）
	 * 自动检查当前用户是否已登录
	 */
	@RequestMapping("/update/info")
	@ResponseBody
	public R updateInfo(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		Integer userId = UserSessionTool.getUserId(userFeignService, request);

		System.out.println("updateInfo: " + userId);

		if(userId == null)
			return R.ok().put("status", "error: no login");

		if(params.get("name") == null || params.get("value") == null)
			return R.ok().put("status", "error: miss parameter");

		if("password".equals(params.get("name").toString())) {
			Map<String, Object> p = new HashMap<>();

			p.put("userId", userId);
			p.put("password", params.get("password"));
			if(!"ok".equals(userFeignService.loginByUserId(p).get("status").toString()))
				return R.ok().put("status", "error: error password");
		}

		params.put("userId", userId);
		return userFeignService.updateInfo(params);
	}

	/**
	 * 设置用户默认收货地址
	 * 自动检查当前用户是否已登录
	 */
	@RequestMapping("/update/defaultAddress")
	@ResponseBody
	public R updateDefaultAddress(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		Integer userId = UserSessionTool.getUserId(userFeignService, request);

		System.out.println("updateDefaultAddress: " + userId);

		if(userId == null)
			return R.ok().put("status", "error: no login");

		if(params.get("addressId") == null)
			return R.ok().put("status", "error: miss parameter");

		params.put("userId", userId);

		return userFeignService.setDefaultAddress(params);
	}

	/**(2020-09-06)
	 * 添加收货地址
	 * 自动检查当前用户是否已登录
	 */
	@RequestMapping("/save/address")
	@ResponseBody
	public R saveAddress(@RequestBody AddressEntity address, HttpServletRequest request) {
		Integer userId = UserSessionTool.getUserId(userFeignService, request);

		System.out.println("saveAddress: " + userId);

		if(userId == null)
			return R.ok().put("status", "error: no login");

		address.setUserId(userId);

		return userFeignService.save(address);
	}

	/**(2020-09-06)
	 * 添加头像
	 * 自动检查当前用户是否已登录
	 */
	@RequestMapping("/save/icon")
	@ResponseBody
	public R saveIcon(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		Integer userId = UserSessionTool.getUserId(userFeignService, request);

		System.out.println("saveIcon: " + userId);

		if(userId == null)
			return R.ok().put("status", "error: no login");

		try {
			String filename = file.getOriginalFilename();
			filename = filename.substring(filename.lastIndexOf('.'));
			filename = userId.toString() + "_user_icon" + filename;
			File iconFile = new File(iconSavePath, filename);

			System.out.println(iconFile.isAbsolute());

			file.transferTo(iconFile);

			Map<String, Object> params = new HashMap<>();
			params.put("userId", userId);
			params.put("name", "userIcon");
			params.put("value", iconBasePath + filename);
			userFeignService.updateInfo(params);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return R.ok();
	}



//	/**(2020-09-09)
//	 * 添加到购物车
//	 * 自动检查当前用户是否已登录
//	 */
//	@RequestMapping("/save/addToShoppingcart")
//	@ResponseBody
//	public R saveAddToShoppingcart(@RequestBody ShoppingCartEntity shoppingcart, HttpServletRequest request) {
//		Integer userId = UserSessionTool.getUserId(userFeignService, request);
//
//		System.out.println("saveAddToShoppingcart: " + userId);
//
//		if(userId == null)
//			return R.ok().put("status", "error: no login").put("message", "no login");
//
//		shoppingcart.setUserId(userId);
//
////		System.out.println(shoppingcart);
//
//		R result = shoppingcartFeignService.save(shoppingcart);
//
//		System.out.println(result);
//
//		return result.get("msg").equals("success") ? R.ok().put("status", "ok") : R.ok().put("status", "error").put("message", "unknow");
//	}
}
